//
//  WXPTotalLoanInfoVC.m
//  MexicoLoan
//
//  Created by wxp on 2025/3/17.
//

#import "WXPTotalLoanInfoVC.h"
#import "WCPTotalLoanInfoHeaderView.h"
#import "WXPTotalLoanInfoCell.h"
#import "WCPTotalLoanInfoFooterView.h"
#import "WXPLoanAgreementVC.h"
#import "WXPSubmitOrderSuccessVC.h"

@interface WXPTotalLoanInfoVC ()

@property (nonatomic, strong) WXPNavView * navView;
@property (nonatomic, assign) BOOL immediatePop;
@property (nonatomic, strong) WXPTwoBtnPopUpWindowView * detainmentView;

@property (nonatomic, strong) UIView * headerView;
@property (nonatomic, strong) WCPTotalLoanInfoHeaderView * topMoneyView;
@property (nonatomic, strong) WXPCommonAgreementView * agreementView;
@property (nonatomic, strong) WCPTotalLoanInfoFooterView * footerView;
@property (nonatomic,   copy) NSString * startTime;
@property (nonatomic,   copy) NSString * agreementHtml;

@end

@implementation WXPTotalLoanInfoVC

#pragma mark - lazy
- (WXPNavView *)navView{
    if (_navView == nil) {
        _navView = [WXPNavView  new];
        [_navView resetViewWithTitle:@"Detalles del préstamo"];
        _navView.leftTop = XY(0, 0);
        WEAKSELF
        _navView.blockPop = ^{
            if(weakSelf.immediatePop){
                [Global_Nav popViewControllerAnimated:true];
            }else{
                // 挽留弹窗
                weakSelf.immediatePop = true;
                [weakSelf.view addSubview:weakSelf.detainmentView];
            }
        };
    }
    return  _navView;
}
- (WXPTwoBtnPopUpWindowView *)detainmentView{
    if (!_detainmentView) {
        _detainmentView = [WXPTwoBtnPopUpWindowView new];
        ModelBtn * model = [ModelBtn new];
        model.title = @"Por favor, reconsidera, ¡la cuota del préstamo seguirá subiendo!";
        model.rightName = @"confirmar";
        model.isHide = false;
        [_detainmentView resetWithModel:model];
        [_detainmentView resetOnlyShowRightBtn];
        WEAKSELF
        _detainmentView.blockRightClick = ^{
            [weakSelf.detainmentView removeFromSuperview];
        };
    }
    return _detainmentView;
}
- (WXPCommonAgreementView *)agreementView{
    if (!_agreementView) {
        _agreementView = [WXPCommonAgreementView new];
        _agreementView.centerXBottom = XY(SCREEN_WIDTH/2, SCREEN_HEIGHT-LEFT_MARDIN);
    }
    return _agreementView;
}
- (UIView *)headerView{
    if (_headerView == nil) {
        _headerView = [UIView  new];
    }
    return  _headerView;
}
- (WCPTotalLoanInfoHeaderView *)topMoneyView{
    if (!_topMoneyView) {
        _topMoneyView = [WCPTotalLoanInfoHeaderView new];
        [_topMoneyView startCountdownTime];
        WEAKSELF
        _topMoneyView.blockSubmint = ^{
            [weakSelf requestApply];
        };
    }
    return _topMoneyView;
}
- (WCPTotalLoanInfoFooterView *)footerView{
    if (!_footerView) {
        _footerView = [WCPTotalLoanInfoFooterView new];
        WEAKSELF
        _footerView.blockJumpToAgreement = ^{
            WXPLoanAgreementVC * vc = [WXPLoanAgreementVC new];
            vc.htmlStr = weakSelf.agreementHtml;
            [Global_Nav pushViewController:vc animated:true];
        };
    }
    return _footerView;
}

#pragma mark - viewDidLoad
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.startTime = [GlobalMethod getTimeStampMillisecond];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    // 打点
    [GlobalMethod hitPointWithPageName:KEY_LoanDetails action:KEY_Enter extInfo:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self configUI];
    //request
    [self requestTotalLoanCalculateFlexible];
}
- (void)dealloc {
    [self.topMoneyView endCountdownTime];
}
- (void)configUI{
    [self.tableView registerClass:[WXPTotalLoanInfoCell class] forCellReuseIdentifier:NSStringFromClass([WXPTotalLoanInfoCell class])];
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = self.viewBG.bounds;
    gradientLayer.colors = @[(id)COLOR_PRIMARY.CGColor, (id)COLOR_BACKGROUND.CGColor];
    gradientLayer.startPoint = CGPointMake(0.5, 0.0);
    gradientLayer.endPoint = CGPointMake(0.5, 1.0);
    [self.viewBG.layer insertSublayer:gradientLayer atIndex:0];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableHeaderTopBg.backgroundColor = [UIColor clearColor];
    self.tableView.height = self.agreementView.top-self.navView.bottom;
    [self.view addSubview:self.navView];
    [self.view addSubview:self.agreementView];
    [self resetHeaderView];
}

#pragma mark - resetHeaderView
- (void)resetHeaderView{
    self.headerView = [UIView initWithViews:@[
        self.topMoneyView,
    ]];
    self.tableView.tableHeaderView = self.headerView;
    self.tableView.tableFooterView = self.footerView;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.aryDatas.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    WXPTotalLoanInfoCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WXPTotalLoanInfoCell class]) forIndexPath:indexPath];
    [cell resetCellWithModel:self.aryDatas[indexPath.row]];
    if (indexPath.row == 0) {
        UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:cell.viewBack.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerTopRight) cornerRadii:CGSizeMake(16, 16)];
        CAShapeLayer *maskLayer = [CAShapeLayer layer];
        maskLayer.path = path.CGPath;
        cell.viewBack.layer.mask = maskLayer;
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [WXPTotalLoanInfoCell getHeight:self.aryDatas[indexPath.row] className:@"" selectorName:@"resetCellWithModel:"];
}
//table header
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return  nil;
}
//table footer
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

#pragma mark - request
// 总借款信息
- (void)requestTotalLoanCalculateFlexible{
    NSMutableArray * reqList = [NSMutableArray new];
    
    for (ModelProductPackageList * model in self.array) {
        NSDictionary * dic = @{
            KEY_amount: strDotF(model.amount),
            KEY_id: strDotF(model.productPackageListIdentifier),
            KEY_term: strDotF(model.term),
        };
        [reqList addObject:dic];
    }
    [RequestApi requestTotalLoanCalculateFlexibleWithAry:reqList delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        
        ModelBtn * model = [ModelBtn new];
        model.title = [response stringValueForKey:KEY_loanAmount];
        model.content = strDotF([response doubleValueForKey:KEY_term]);
        [self.topMoneyView resetView:model];
        [self resetHeaderView];
        
        self.aryDatas = [GlobalMethod exchangeDic:[response arrayValueForKey:KEY_pairs] toAryWithModelName:@"ModelPairs"];
        [self.tableView reloadData];
        
        // 风控埋点
        [GlobalMethod addRiskControlWithType:KEY_BEGIN_LOAN startTime:self.startTime endTime:[GlobalMethod getTimeStampMillisecond]];
        
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
    
    // 获取借款协议参数
    [RequestApi requestContractLoanHtmlInfoWithReqList:reqList delegate:nil success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {
        int term = [response intValueForKey:KEY_term];
        NSString * apr = [response stringValueForKey:KEY_apr];
        NSString * repaymentPlanTime = [response stringValueForKey:KEY_repaymentPlanTime];
        repaymentPlanTime = [GlobalMethod exchangeTimestamp:repaymentPlanTime formate:TIME_DAY_MONTH_YEAR];
        int loanAmount = [response intValueForKey:KEY_loanAmount];
        int actualAmount = [response intValueForKey:KEY_actualAmount];
        NSString * termUnitStr = @"Días";
        self.agreementHtml = [NSString stringWithFormat:@"/contract/loan.html?term=%d%@&apr=%@&repaymentPlanTime=%@&loanAmount=%@&actualAmount=%@",term, termUnitStr, readStr(apr), readStr(repaymentPlanTime), [GlobalMethod showMoney:[NSString stringWithFormat:@"%d",loanAmount]], [GlobalMethod showMoney:[NSString stringWithFormat:@"%d",actualAmount]]];
    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {
        
    }];
}

// 申请借款
- (void)requestApply{
    NSString * startTime = [GlobalMethod getTimeStampMillisecond];
    [GlobalMethod hitPointWithPageName:KEY_LoanDetails action:KEY_Apply_Loan_Click extInfo:nil];
    NSMutableArray * array = [NSMutableArray array];
    for (ModelProductPackageList * model in self.array) {
        NSDictionary * dic = @{
            KEY_applyAmount: strDotF(model.amount),
            KEY_isReloan: strDotF(model.isReloan),
            KEY_productId: strDotF(model.productPackageListIdentifier),
            KEY_term: strDotF(model.term),
            KEY_termUnit: strDotF(model.termUnit)
        };
        [array addObject:dic];
    }
    [RequestApi requestApplyWithAry:array delegate:self success:^(NSDictionary * _Nonnull response, id  _Nonnull mark) {

        [GlobalMethod hitPointWithPageName:KEY_LoanDetails action:KEY_Apply_Loan_Success extInfo:nil];
        // 风控埋点
        [GlobalMethod addRiskControlWithType:KEY_END_LOAN startTime:startTime endTime:[GlobalMethod getTimeStampMillisecond]];
        
        // 申请成功
        WXPSubmitOrderSuccessVC * vc = [WXPSubmitOrderSuccessVC new];
        BOOL isShowMark = [response[RESPONSE_DATA] boolValue];
        vc.isShowScoreView = isShowMark;
        [Global_Nav pushViewController:vc animated:true];

    } failure:^(NSString * _Nonnull errorStr, id  _Nonnull mark) {

    }];
}

@end



